<?php

/**
 * ContactForm class.
 * ContactForm is the data structure for keeping
 * contact form data. It is used by the 'contact' action of 'SiteController'.
 */
class Product extends ActiveRecord
{
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}
	
	public function tableName()
	{
		return 'product';
	}
	
	public function rules()
	{
		return array(
		);
	}

	public function search()
	{   
            $condition = "";            

            if(!empty($_POST['_name']))
                $condition .= " AND t.name LIKE '%" . trim($_POST['_name']) . "%'";
            
            if(!empty($_POST['_categoryId']))
                $condition .= " AND t.categoryId=" . $_POST['_categoryId'];
            
		$query = "SELECT t.id, t.name, t.createdDate, c.name as categoryName
                        FROM product t
                        JOIN category c ON c.id = t.categoryId
                        WHERE 1=1 $condition
		";
		
		$result = $this -> executeAllTotal($query, array(), true, "t.createdDate DESC");
	
		return $result;
	}
	
	public function getItem($id)
	{
		$query = "
			SELECT t.*, c.name as categoryName
			FROM product t
			JOIN category c ON c.id = t.categoryId
			WHERE t.id = $id
		";
		
		$result = $this -> executeRow($query);
	
		return $result;
	}
	
	public function getItemsByCategoryId($cid)
	{
		$query = "
			SELECT t.id, t.name, t.categoryId, t.imageUrl
			FROM product t			
			WHERE t.categoryId = $cid
		";
		
		$result = $this -> executeAll($query);
	
		return $result;
	}
        
        public function getItemsByCategoryId1($cid, $rpg, $page)
	{
		$query = "SELECT t.id, t.name, t.categoryId, t.imageUrl
			FROM product t			
			WHERE t.categoryId = $cid
		";
		
                $start = $rpg * ($page - 1);
                
		$result = $this ->executeAllTotal($query, array(), true, "t.imageType ASC, t.createdDate ASC", $start, $rpg);
	
		return $result;
	}
        
        public function deleteByIds($ids = "")
	{
            if($ids == "") return false;
            
            $query = "
            	DELETE product
            	WHERE id IN ($ids)
            ";
		
            $result = $this -> executeNone($query);
            
            Category::model() -> updateProductCount();
            
            return true;
	}
}